<template>
  <div class="albumDetail" v-title :data-title="$t('router.albumTitle')">
    <div class="Breadcrumbback">
      <Breadcrumb></Breadcrumb>
    </div>
    <div class="main">
      <div class="top">
        <div class="image">
          <el-image
            :key="detailData.cover500 || detailData.cover200"
            :src="detailData.cover500 || detailData.cover200"
            :preview-src-list="[detailData.cover500]"
            fit="contain"
          >
            <div slot="placeholder" class="image-slot flex-center flex-column">
              <i class="iconfont el-icon-loading"></i>
              <p>
                {{ $t("public.loading") }}
                <span class="dot">...</span>
              </p>
            </div>
            <div slot="error" class="image-slot flex-center">
              <img src="@/assets/images/defaultCover.png" />
            </div>
          </el-image>
        </div>
        <div class="info">
          <h2
            class="ellipsis-two"
            v-text="
              $i18n.locale === 'zh'
                ? detailData.catalogueCname || detailData.catalogueName
                : detailData.catalogueName
            "
          ></h2>
          <li class="info-text">
            <p>
              <!-- :class="isBooklet ? 'booklet' : 'disabled'" -->
              <el-button
                @click="getBooklets('booklet')"
                type="text"
                :disabled="!isBooklet"
                class="booklet"
                >{{ $t("main.booklet") }}</el-button
              >
              <!-- :class="isBack ? 'back' : 'disabled'" -->
              <el-button
                @click="getBooklets('back')"
                type="text"
                :disabled="!isBack"
                class="back"
                >{{ $t("main.backCover") }}</el-button
              >
            </p>
            <span class="albumNum" v-text="$route.params.id"></span>
          </li>
          <li class="info-text">
            <!-- :disabled="true" -->
            <!-- type="info" -->
            <el-button
              icon="el-icon-download"
              @click="openDialog('downloadAll', detailData)"
              type="primary"
              size="small"
              >{{ $t("main.downloadAlbum") }}</el-button
            >
            <el-button
              type="primary"
              v-if="playParentId == $route.params.id && playing"
              class="icon-button"
              size="small"
              @click="play('pauseAll')"
              ><svg-icon name="pause" class="icon icon-pause" />{{
                $t("public.pause")
              }}</el-button
            >
            <el-button
              v-else
              type="primary"
              class="icon-button"
              size="small"
              @click="play('playAll')"
              ><svg-icon name="play" class="icon icon-play" />{{
                $t("public.play")
              }}</el-button
            >
            <el-button
              type="primary"
              class="icon-button"
              @click="openDialog('addDisks')"
              size="small"
              ><svg-icon name="add" class="icon icon-add" />{{
                $t("main.addToRecordClip")
              }}</el-button
            >
            <el-button
              type="primary"
              class="icon-button"
              size="small"
              @click="
                isLikeAlbum(
                  $route.params.id,
                  detailData.likeState,
                  detailData.moduleId
                )
              "
            >
              <svg-icon
                :name="detailData.likeState ? 'is-like' : 'like'"
                class="icon icon-like"
              />
              {{
                detailData.likeState
                  ? $t("main.haveBeenLike")
                  : $t("main.addToWhatILike")
              }}</el-button
            >
            <el-button
              type="primary"
              @click="openConfirm('addPlayListAll')"
              class="icon-button"
              size="small"
              ><svg-icon name="play-list" class="icon icon-play-list" />{{
                $t("public.addToPlaylist")
              }}</el-button
            >
            <el-button
              type="primary"
              @click="openDialog('share')"
              class="icon-button"
              size="small"
              ><svg-icon name="share" class="icon icon-share" />{{
                $t("main.share")
              }}</el-button
            >
          </li>
        </div>
      </div>
      <!-- @tab-click="handleClick" -->
      <el-tabs
        class="box content"
        v-model="activeName"
        v-loading="fullscreenLoading"
      >
        <el-tab-pane
          :label="$t('main.single') + '(' + singleNum + ')'"
          name="first"
          class="first"
        >
          <h6 @click="openAllName">
            {{ $t("public.artistDetails") }}
            <svg-icon
              :name="isActiveAll ? 'on-detail' : 'off-detail'"
              class="icon icon-off-detail"
            />
          </h6>
          <div class="checkAll">
            <!-- :indeterminate="isIndeterminate" -->
            <el-checkbox v-model="checkAll" @change="handleCheckAllChange">{{
              checkAll ? $t("main.deselectAll") : $t("main.selectAll")
            }}</el-checkbox>
            <el-button
              type="primary"
              size="small"
              @click="openDialog('addSingles')"
              >{{ $t("main.addToSingleClip") }}</el-button
            >
            <el-button
              type="primary"
              @click="openConfirm('addPlayList')"
              size="small"
              >{{ $t("public.addToPlaylist") }}</el-button
            >
          </div>
          <p class="pArtist ellipsis">
            <span
              v-for="item of detailData.artists"
              :key="item.fullName"
              v-text="
                $i18n.locale === 'zh'
                  ? item.fullCname || item.fullName
                  : item.fullName
              "
            ></span>
          </p>
          <!-- highlight-current-row -->
          <!-- @current-change="handleCurrentChange" -->
          <el-table
            class="album-detail-table singleTable"
            ref="songListTable"
            v-for="item of detailData.works"
            :key="item.workId"
            :data="item.compositions"
            @select="selectionChange"
            @select-all="selectionChangeAll(item)"
            height="auto"
          >
            <el-table-column type="selection" width="100"> </el-table-column>
            <el-table-column min-width="74%" show-overflow-tooltip>
              <template #header>
                <span class="isWorkName" @click="openWorkName(item.workId)">
                  <svg-icon
                    :name="
                      activeId == item.workId || isActiveAll
                        ? 'on-detail'
                        : 'off-detail'
                    "
                    class="icon icon-off-detail"
                  />
                  {{
                    $i18n.locale === "zh"
                      ? item.workCname || item.workName
                      : item.workName
                  }}
                </span>
                <p
                  class="isSingleName isWorkName"
                  v-show="item.workId == activeId || isActiveAll"
                >
                  <span
                    v-for="(i, idx) in item.compositions[0].composer"
                    :key="idx"
                    v-text="
                      $i18n.locale === 'zh'
                        ? i.fullCname || i.fullName
                        : i.fullName
                    "
                  ></span>
                </p>
              </template>
              <template slot-scope="scope">
                <span class="workIndex">{{ scope.$index + 1 }}</span>
                <span
                  class="isWorkName"
                  @click="openSingleName(scope.row.trackId)"
                >
                  <svg-icon
                    :name="
                      scope.row.trackId == activeId || isActiveAll
                        ? 'on-detail'
                        : 'off-detail'
                    "
                    class="icon icon-off-detail"
                  />
                  {{
                    $i18n.locale === "zh"
                      ? scope.row.trackCtitle || scope.row.trackTitle
                      : scope.row.trackTitle
                  }}
                </span>
                <p
                  class="isSingleName"
                  v-show="scope.row.trackId == activeId || isActiveAll"
                >
                  <span
                    v-for="(i, idx) in scope.row.composer"
                    :key="idx"
                    v-text="
                      $i18n.locale === 'zh'
                        ? i.fullCname || i.fullName
                        : i.fullName
                    "
                  ></span>
                </p>
              </template>
            </el-table-column>
            <!-- 喜欢按钮 -->
            <el-table-column min-width="4%">
              <template slot-scope="scope">
                <svg-icon
                  @click="isLikeSingle(scope.row.trackId, scope.row.likeState)"
                  :name="scope.row.likeState ? 'is-like' : 'like'"
                  class="icon icon-like"
                />
              </template>
            </el-table-column>
            <!-- 播放按钮 -->
            <el-table-column min-width="4%">
              <template slot-scope="scope">
                <div
                  :class="
                    currentSong.trackId == scope.row.trackId && playing
                      ? 'playing'
                      : ''
                  "
                >
                  <svg-icon
                    @click="play('pause', scope.row)"
                    name="pause"
                    class="icon icon-pause"
                  />
                  <svg-icon
                    @click="play('play', scope.row)"
                    name="play"
                    class="icon icon-play"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column min-width="4%">
              <template slot-scope="scope">
                <svg-icon
                  @click="openDialog('download', scope.row)"
                  name="download"
                  class="icon icon-download"
                />
              </template>
            </el-table-column>
            <el-table-column
              min-width="10%"
              prop="timing"
              show-overflow-tooltip
              :label="utils.formatSecondTime(item.totalTiming)"
            ></el-table-column>
            <!-- :label="item.createTime ? item.createTime : '时长'" -->
          </el-table>
        </el-tab-pane>

        <el-tab-pane
          :label="$t('main.albumDetails')"
          name="second"
          class="second"
        >
          <ul>
            <li>
              <span>{{ $t("public.classify") }}：</span>
              <p
                v-if="detailData.categories && detailData.categories.length > 0"
              >
                <span
                  v-for="item of detailData.categories"
                  :key="item.categoryName"
                  v-text="
                    $i18n.locale === 'zh'
                      ? item.categoryCname || item.categoryName
                      : item.categoryName
                  "
                ></span>
              </p>
              <p v-else>{{ $t("public.noInformation") }}</p>
            </li>
            <li>
              <span>{{ $t("public.composer") }}：</span>
              <p v-if="detailData.arrangers && detailData.arrangers.length > 0">
                <span
                  v-for="item of detailData.arrangers"
                  :key="item.fullName"
                  v-text="
                    $i18n.locale === 'zh'
                      ? item.fullCname || item.fullName
                      : item.fullName
                  "
                ></span>
              </p>
              <p v-else>{{ $t("public.noInformation") }}</p>
            </li>
            <li>
              <span>{{ $t("public.artist") }}：</span>
              <p v-if="detailData.artists && detailData.artists.length > 0">
                <span
                  v-for="item of detailData.artists"
                  :key="item.fullName"
                  v-text="
                    $i18n.locale === 'zh'
                      ? item.fullCname || item.fullName
                      : item.fullName
                  "
                ></span>
              </p>
              <p v-else>{{ $t("public.noInformation") }}</p>
            </li>
            <li>
              <span>{{ $t("public.brand") }}：</span>
              <p v-if="detailData.musicLabel">
                <span v-text="detailData.musicLabel.displayName"></span>
              </p>
              <p v-else>{{ $t("public.noInformation") }}</p>
            </li>
            <li>
              <span>{{ $t("main.albumNo") }}：</span>
              <p>{{ $route.params.id || $t("public.noInformation") }}</p>
            </li>
            <li>
              <span>{{ $t("main.issueDate") }}：</span>
              <p>
                {{
                  formateDate(detailData.releaseDate) ||
                  $t("public.noInformation")
                }}
              </p>
            </li>
          </ul>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- <drawer-list :isPlayer="true"></drawer-list> -->

    <!--弹窗界面-->
    <el-dialog
      :width="isQrcode ? '28%' : '20%'"
      :title="$t(textMap[dialogStatus])"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <!-- 下载弹窗 -->
      <el-form
        v-if="
          dialogStatus == 'download' ||
          dialogStatus == 'downloadAll' ||
          dialogStatus == 'booklet'
        "
        :model="download"
        class="download"
        :rules="rules"
        :ref="dialogStatus"
      >
        <el-form-item :label="$t('public.account')" prop="account">
          <el-input
            v-model="download.account"
            :placeholder="$t('public.enterAccount')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.password')" prop="password">
          <el-input
            v-model="download.password"
            show-password
            :placeholder="$t('public.enterPassword')"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加到唱片夹 -->
      <el-form
        v-else-if="dialogStatus == 'addDisks'"
        :model="addDisks"
        class="addDisks"
        :rules="rules"
        ref="addDisks"
      >
        <el-form-item prop="selectDisks">
          <el-select
            v-model="addDisks.selectDisks"
            clearable
            filterable
            :placeholder="$t('public.selectDisks')"
          >
            <el-option
              v-for="item in options"
              :key="item.dirId"
              :label="item.name"
              :value="item.dirId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="addDisks.selectDisks === '0'"
          :label="$t('public.newDisks')"
          prop="nameDisks"
        >
          <el-input
            class="input-new-tag"
            v-model="addDisks.nameDisks"
            maxlength="20"
            show-word-limit
            :placeholder="$t('main.enterRecordClipName')"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 分享 -->
      <ul class="dialogShare" ref="share" v-else-if="dialogStatus == 'share'">
        <li @click="share('weixin')">
          <img src="@/assets/images/wx.png" alt="WeChat" />
        </li>
        <li @click="share('weibo')">
          <img src="@/assets/images/weibo.png" alt="WeiBo" />
        </li>
        <li @click="share('qq')">
          <img src="@/assets/images/qq.png" alt="QQ" />
        </li>
      </ul>
      <!-- 添加到单曲夹 -->
      <el-form
        v-else-if="dialogStatus == 'addSingles'"
        :model="addSingles"
        class="addSingles"
        :rules="rules"
        ref="addSingles"
      >
        <el-form-item prop="selectSingles">
          <el-select
            v-model="addSingles.selectSingles"
            clearable
            filterable
            :placeholder="$t('public.selectSingles')"
          >
            <el-option
              v-for="item in options"
              :key="item.dirId"
              :label="item.name"
              :value="item.dirId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="addSingles.selectSingles === '0'"
          :label="$t('public.newSingles')"
          prop="nameSingles"
        >
          <el-input
            class="input-new-tag"
            v-model="addSingles.nameSingles"
            maxlength="20"
            show-word-limit
            :placeholder="$t('main.enterSingleClipName')"
          ></el-input>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        :class="
          dialogStatus == 'share' ? 'share-dialog-footer' : 'dialog-footer'
        "
      >
        <el-button
          class="clearBtn"
          @click.native="
            dialogFormVisible = false;
            isQrcode = false;
          "
          >{{ $t("public.cancel") }}</el-button
        >
        <el-button type="primary" @click="createData(dialogStatus)">{{
          $t("public.save")
        }}</el-button>
        <!-- <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button> -->
      </div>
      <p class="qrcodeText" v-if="isQrcode">
        <span v-show="qrcodeText === 'wx'">
          {{ $t("main.openWechatScan") }}
        </span>
        <span v-show="qrcodeText === 'qq'">
          {{ $t("main.scanQQ") }}
        </span>
      </p>
      <div id="qrcode" ref="qrcode" v-show="isQrcode"></div>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "@/components/common/Breadcrumb/Index";
// import drawerList from "@/components/common/drawerList/Index";
import { mapMutations, mapGetters, mapActions } from "vuex";
import QRCode from "qrcodejs2";
// import { parse } from 'qs';
export default {
  name: "albumDetail",
  data() {
    return {
      activeName: "first",
      detailData: {}, //专辑详情数据
      checkAll: false,
      multipleSelection: [], //多选
      // isIndeterminate: false, //全选/部分选状态
      // 当前选中行
      currentRow: null,
      isActiveAll: false, //展开所有Name
      activeId: -1, //展开单个Name
      fullscreenLoading: false, //数据载入动画
      // el-dialog相关
      textMap: {
        //添加与编辑界面
        download: "public.passwordAuthentification", //'public.edit'
        downloadAll: "public.passwordAuthentification",
        booklet: "public.passwordAuthentification",
        addDisks: "main.addToRecordClip",
        share: "main.share",
        addSingles: "main.addToSingleClip",
      },
      options: [], //单曲夹/唱片夹弹框下拉
      dialogFormVisible: false, //弹窗
      dialogStatus: "", //编辑框界面切换
      //弹窗界面数据
      download: {
        roleId: "0", //待定
        account: "",
        password: "",
      },
      addDisks: {
        selectDisks: "",
        nameDisks: "",
      },
      addSingles: {
        selectSingles: "",
        nameSingles: "",
      },
      singleNum: 0, //单曲数量
      // 音乐播放器
      // playInfo: {},
      // playList: [],
      isBooklet: false, //是否显示小册子
      isBack: false, //是否显示封面图像
      flag: false, // 标记首次加载
      downParams: {}, // 下载参数
      // 获取要下载的单曲信息
      currentSingle: [
        {
          name: "", // 单曲名(文件名)
          trackId: "", //单曲ID
          quality: "", //音质：320、192、hifi
        },
      ],
      isQrcode: false, //是否显示二维码
      qrcodeText: "",
      titleText: "router.kuKeTitle",
    };
  },
  components: {
    Breadcrumb,
    // drawerList,
  },
  computed: {
    ...mapGetters([
      "loginStatu",
      "userInfo",
      "playLists",
      "playing",
      "currentSong",
      "playParentId",
    ]),
    rules() {
      return {
        account: [
          {
            required: true,
            message: this.$t("public.accountEmpty"),
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: this.$t("public.passwordEmpty"),
            trigger: "blur",
          },
        ],
        selectDisks: [
          {
            required: true,
            message: this.$t("public.selectDisks"),
            trigger: "blur",
          },
        ],
        selectSingles: [
          {
            required: true,
            message: this.$t("public.selectSingles"),
            trigger: "blur",
          },
        ],
        nameDisks: [
          {
            required: true,
            message: this.$t("public.disksCannotEmpty"),
            trigger: "blur",
          },
        ],
        nameSingles: [
          {
            required: true,
            message: this.$t("public.SinglesCannotEmpty"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  watch: {},
  created() {},
  mounted() {
    this.getDetail();
    if (this.loginStatu) {
      this.getBooklets();
    }
    if (this.detailData.moduleId === 516) {
      this.titleText = "router.albumClassicalTitle";
    } else if (this.detailData.moduleId === 518) {
      this.titleText = "router.albumNationalTitle";
    } else if (this.detailData.moduleId === 580) {
      this.titleText = "router.albumJazzTitle";
    } else if (this.detailData.moduleId === 517) {
      this.titleText = "router.albumAudioBookTitle";
    }
  },
  methods: {
    ...mapMutations({
      setPlayList: "SET_PLAYLIST",
      setDialogLogin: "SET_DIALOGLOGIN",
      setPlayParentId: "SET_PLAY_PARENT_ID",
      setPlayClipId: "SET_PLAY_CLIP_ID",
    }),
    ...mapActions([
      // 点击选择播放
      "selectPlay",
      // 点击播放全部
      "playAll",
      "playStatus",
      "savePlayList",
    ]),
    async getDetail() {
      this.fullscreenLoading = true;
      try {
        let params = {
          catalogueId: this.$route.params.id,
        };
        let res;
        let sort = this.$route.params.sort;
        // let moduleId = this.$route.params.moduleId;
        if (
          // sort == "classicalAlbum" ||
          // sort == "classicalSortList" ||
          // sort == "classicalBrandDetail" ||
          // sort == "classicalResource"
          // moduleId == 516
          sort == "classical" ||
          sort == "classicalSortList" ||
          sort == "classicalBrandDetail"
        ) {
          res = await this.$api.classical.musicAlbumInfo(params);
        } else if (
          sort == "national" ||
          sort == "nationalCultureList" ||
          sort == "nationalBrandDetail"
        ) {
          res = await this.$api.national.musicAlbumInfo(params);
        } else if (
          sort == "jazz" ||
          sort == "jazzSortList" ||
          sort == "jazzBrandDetail"
        ) {
          res = await this.$api.jazz.musicAlbumInfo(params);
        } else if (sort == "audio-book") {
          res = await this.$api.audioBooks.musicAlbumInfo(params);
        }
        if (res.code === 1000000) {
          this.detailData = res.source ? res.source : {};
          this.fullscreenLoading = false;
          this.multipleSelection = [];
          this.checkAll = false;
          this.singleNum = 0;
          this.detailData.works.forEach((item) => {
            this.singleNum += item.compositions.length;
            item.totalTiming = 0;
            item.compositions.forEach((val) => {
              item.totalTiming += this.utils.formatTimestamp(val.timing);
            });
          });
        }
      } catch (e) {
        console.log(e);
      }
    },
    // tab切换
    // handleClick(tab, event) {
    //   console.log(tab, event);
    // },
    // 全选
    handleCheckAllChange(val) {
      if (val) {
        let arr = [];
        this.detailData.works.forEach((item, idx) => {
          item.compositions.forEach((row) => {
            arr.push(row);
            this.$refs.songListTable[idx].toggleRowSelection(row, true);
          });
        });
        this.multipleSelection = arr;
      } else {
        for (let idx in this.detailData.works) {
          this.multipleSelection = [];
          this.$refs.songListTable[idx].clearSelection();
        }
      }
      // let list = val ? this.detailData.works : [];
      // this.isIndeterminate = false;
      // console.log(list)
      // this.handleSelectionChange(list)
    },
    // 列表单选选中触发事件
    // handleCurrentChange(val) {
    //   this.currentRow = val;
    // },
    selectionChange(val, row) {
      let result = this.multipleSelection.some((i, idx) => {
        if (i.trackId == row.trackId) {
          this.multipleSelection.splice(idx, 1);
          return true;
        }
      });
      if (result == false) {
        this.multipleSelection.push(row);
      }
      this.checkAll = this.multipleSelection.length === this.singleNum;
    },
    // 单表格全选
    selectionChangeAll(val) {
      let flag; // true添加-未全选
      val.compositions.forEach((x) => {
        // flag = false;
        let result = this.multipleSelection.findIndex((y) => {
          return x.trackId == y.trackId;
        });
        if (result == -1) {
          flag = true;
          return;
        }
      });
      if (flag || this.multipleSelection.length < val.compositions.length) {
        //添加=全选中
        this.multipleSelection = this.utils.processingData(
          this.multipleSelection,
          val.compositions
        );
      } else {
        val.compositions.forEach((n) => {
          let index = this.multipleSelection.findIndex((k) => {
            return n.trackId == k.trackId;
          });
          this.multipleSelection.splice(index, 1);
        });
      }
      this.checkAll = this.multipleSelection.length === this.singleNum;
    },
    // 艺术家详情  展开所有Name
    openAllName() {
      this.isActiveAll = !this.isActiveAll;
    },
    // 展开所有作品Name 单个
    openWorkName(idx) {
      this.isActiveAll = false;
      if (idx == this.activeId) {
        this.activeId = -1;
      } else {
        this.activeId = idx;
      }
    },
    // 展开所有单曲Name 单个
    openSingleName(idx) {
      this.isActiveAll = false;
      if (idx == this.activeId) {
        this.activeId = -1;
      } else {
        this.activeId = idx;
      }
    },
    // 打开弹窗界面
    async openDialog(type, item) {
      if (!this.loginStatu) {
        this.setDialogLogin(true);
        return;
      }
      this.dialogStatus = type;
      let res;
      if (type == "share") {
        this.dialogFormVisible = true;
        return;
      } else if (type == "addDisks") {
        res = await this.$api.user.getDirList({ type: 1 });
        if (res.code === 1000000) {
          if (res.source && res.source.length > 0) {
            this.options = res.source;
            this.options.unshift({
              name: this.$t("public.newDisks"),
              dirId: "0",
            });
            this.addDisks.selectDisks = "";
          } else {
            this.options = [
              {
                name: this.$t("public.newDisks"),
                dirId: "0",
              },
            ];
            this.addDisks.selectDisks = "0";
          }
          this.dialogFormVisible = true;
          this.$nextTick(() => {
            this.$refs.addDisks.resetFields();
            this.addDisks.nameDisks = "";
          });
        } else {
          this.$message({
            showClose: true,
            message: this.$t("main.failedRecordHolderList"),
            type: "warning",
          });
        }
      } else if (type == "addSingles") {
        if (this.multipleSelection.length > 0) {
          res = await this.$api.user.getDirList({ type: 2 });
          if (res.code === 1000000) {
            if (res.source && res.source.length > 0) {
              this.options = res.source;
              this.options.unshift({
                name: this.$t("public.newSingles"),
                dirId: "0",
              });
              this.addSingles.selectSingles = "";
            } else {
              this.options = [
                {
                  name: this.$t("public.newSingles"),
                  dirId: "0",
                },
              ];
              this.addSingles.selectSingles = "0";
            }
            this.dialogFormVisible = true;
            this.$nextTick(() => {
              this.$refs.addSingles.resetFields();
              this.addSingles.nameSingles = "";
            });
          } else {
            // this.options.unshift({
            //   name: "新建文件夹",
            //   dirId: "0",
            // });
            // this.addSingles.select = "0";
            // 列表获取失败
            this.$message({
              showClose: true,
              message: this.$t("public.singleFolderFailed"),
              type: "warning",
            });
          }
        } else {
          // 未选择添加单曲
          this.$message({
            showClose: true,
            message: this.$t("public.selectAddSingle"),
            type: "warning",
          });
          return;
        }
      } else if (type == "download") {
        this.downParams = {
          downloadType: 511,
          contents: [
            {
              contentId: item.trackId,
              moduleId: this.detailData.moduleId,
            },
          ],
          theWay: 2, //1账号下载，2非账号下载
        };
        this.downInfo(this.downParams, "download", item);
        // 下载权限校验与明细记录
      } else if (type == "booklet") {
        this.downParams = {
          downloadType: 514,
          contentId: this.$route.params.id,
          moduleId: this.detailData.moduleId,
          theWay: 2, //1账号下载，2非账号下载
        };
        this.downInfo(this.downParams, "booklet");
      } else if (type == "downloadAll") {
        this.downParams = {
          downloadType: 510,
          contentId: this.$route.params.id,
          moduleId: this.detailData.moduleId,
          theWay: 2, //1账号下载，2非账号下载
        };
        this.downInfo(this.downParams, "downloadAll", item);
      }
    },
    // 保存不同下载信息
    async downInfo(params, type, item) {
      if (type == "download" && item) {
        // 保存当前下载单曲信息
        let downInfo = {
          name:
            this.$i18n.locale === "zh"
              ? item.trackCtitle || item.trackTitle
              : item.trackTitle,
          trackId: item.trackId,
          quality:
            item.hifi == 1
              ? "hifi"
              : item.kbps320 == 1
              ? "320"
              : item.kbps192 == 1
              ? "192"
              : item.kbps64
              ? "64"
              : "",
        };
        this.currentSingle = [downInfo];
      } else if (type == "downloadAll" && item) {
        this.currentSingle = [];
        // 取专辑下的所有单曲的集合
        let arr = [];
        let list = arr.concat(
          ...this.detailData.works
            .filter((i) => Boolean(i.compositions))
            .map((i) => i.compositions)
        );
        list.forEach((i) => {
          this.currentSingle.push({
            name:
              this.$i18n.locale === "zh"
                ? i.trackCtitle || i.trackTitle
                : i.trackTitle,
            trackId: i.trackId,
            quality:
              i.hifi == 1
                ? "hifi"
                : i.kbps320 == 1
                ? "320"
                : i.kbps192 == 1
                ? "192"
                : i.kbps64
                ? "64"
                : "",
          });
        });
      }
      let res = await this.$api.user.userDownloadCheck(params);
      // 不需要账密(不弹框)
      if (res.code === 1000000) {
        this.dialogFormVisible = false;
        this.createData(type);
      } else if (res.code === 1701001) {
        this.$message({
          showClose: true,
          message: this.$t("public.downFailed"),
          type: "error",
        });
      } else if (res.code === 1701002) {
        // 需要账密弹框
        this.dialogFormVisible = true;
        // 如果打开弹框 重置表单规则
        this.$nextTick(() => {
          this.$refs[type].resetFields();
        });
        this.downParams.theWay = 1;
      } else if (res.code === 1701003) {
        this.$message({
          showClose: true,
          message: this.$t("public.downBalanceInsufficient"),
          type: "error",
        });
      } else if (res.code === 1701004) {
        this.$message({
          showClose: true,
          message: this.$t("public.accountPasswordIncorrect"),
          type: "error",
        });
      } else if (res.code === 1000002) {
        this.$notify({
          title: this.$t("public.warning"),
          message:
            this.detailData.moduleId == 516
              ? this.$t("public.classicalValidityExpires")
              : this.detailData.moduleId == 518
              ? this.$t("public.worldNationValidityExpires")
              : this.detailData.moduleId == 580
              ? this.$t("public.JazzValidityExpires")
              : this.detailData.moduleId == 517
              ? this.$t("public.audioBooksValidityExpires")
              : this.$t("public.moduleValidityExpires"),
          type: "warning",
          offset: 100,
        });
      }
    },
    //弹窗 提交按钮
    async createData(type) {
      // 需要输入账密验证
      if (this.dialogFormVisible) {
        this.$refs[type].validate(async (valid) => {
          if (valid) {
            let params;
            // 唱片夹
            if (type == "addDisks") {
              if (this.addDisks.selectDisks === "0") {
                let param = {
                  name: this.addDisks.nameDisks,
                  type: 1,
                };
                let res = await this.$api.user.addDir(param);
                if (res.code === 1000000) {
                  params = {
                    userDirChildAdds: {
                      moduleId: this.detailData.moduleId,
                      contentId: this.$route.params.id,
                    },
                    dirId: res.source,
                    type: 1,
                  };
                } else if (res.code === 1700401) {
                  this.$message({
                    showClose: true,
                    message: this.$t("public.recordExists"),
                    type: "error",
                  });
                }
              } else {
                params = {
                  userDirChildAdds: {
                    moduleId: this.detailData.moduleId,
                    contentId: this.$route.params.id,
                  },
                  dirId: this.addDisks.selectDisks,
                  type: 1,
                };
              }
            } else if (type == "addSingles") {
              //单曲夹
              if (this.addSingles.selectSingles === "0") {
                let param = {
                  name: this.addSingles.nameSingles,
                  type: 2,
                };
                let res = await this.$api.user.addDir(param);
                if (res.code === 1000000) {
                  params = {
                    userDirChildAdds: this.multipleSelection.map((item) => {
                      return Object.assign(
                        {},
                        { moduleId: this.detailData.moduleId },
                        { contentId: item.trackId }
                      );
                    }),
                    dirId: res.source,
                    type: 2,
                  };
                } else if (res.code === 1700401) {
                  this.$message({
                    showClose: true,
                    message: this.$t("public.singleExists"),
                    type: "error",
                  });
                }
              } else {
                params = {
                  userDirChildAdds: this.multipleSelection.map((item) => {
                    return Object.assign(
                      {},
                      { moduleId: this.detailData.moduleId },
                      { contentId: item.trackId }
                    );
                  }),
                  dirId: this.addSingles.selectSingles,
                  type: 2,
                };
              }
            } else if (
              type == "download" ||
              type == "downloadAll" ||
              type == "booklet"
            ) {
              this.downParams.account = this.download.account;
              this.downParams.password = this.download.password;
              this.downInfo(this.downParams, type);
              return false;
            }
            // 添加唱片夹与单曲夹
            let res = await this.$api.user.addDirChild(params);
            if (res.code === 1000000) {
              this.$message({
                showClose: true,
                message: this.$t("public.addSuccess"),
                type: "success",
              });
              this.dialogFormVisible = false;
              this.getDetail();
            } else {
              this.$message({
                showClose: true,
                message: this.$t("public.addFailed"),
                type: "success",
              });
            }
          }
        });
      } else {
        if (type == "download") {
          // 单个下载
          let param = {
            trackId: this.currentSingle[0].trackId,
            quality: this.currentSingle[0].quality,
            terminal: "Web",
          };
          let res = await this.$api.user.musicAddress(param);
          if (res.data) {
            this.dialogFormVisible = false;
            this.$message({
              showClose: true,
              message: this.$t("public.downloading"),
            });
            this.utils.downRow(res.data, this.currentSingle[0].name, "mp3");
          } else {
            this.$message({
              showClose: true,
              message: this.$t("public.addressFailed"),
              type: "error",
            });
          }
        } else if (type == "downloadAll") {
          //批量下载
          this.dialogFormVisible = false;
          let batchArr = [];
          for (let item of this.currentSingle) {
            let res = await this.$api.user.musicAddress({
              trackId: item.trackId,
              quality: item.quality,
              terminal: "Web",
            });
            if (res.data) {
              batchArr.push({
                name: item.name,
                url: res.data,
              });
            }
            // URL获取失败提示
            // else {
            //   this.$message.error(item.name + this.$t("public.addressFailed"));
            // }
          }
          this.$message({
            showClose: true,
            message: this.$t("public.downloading"),
          });
          this.utils.batch(batchArr, "mp3");
        } else if (type === "booklet") {
          this.dialogFormVisible = false;
          this.utils.downRow(
            this.isBooklet,
            this.$i18n.locale === "zh"
              ? this.detailData.catalogueCname || this.detailData.catalogueName
              : this.detailData.catalogueName,
            "pdf"
          );
          // window.open(this.isBooklet, "_blank");
          // this.utils.downRow(this.isBooklet, this.$i18n.locale === 'zh'
          //       ? this.detailData.catalogueCname || this.detailData.catalogueName
          //       : this.detailData.catalogueName, "pdf");
        }
      }
    },
    // 是否添加我喜欢   专辑
    async isLikeAlbum(id, status, mId) {
      if (!this.loginStatu) {
        this.setDialogLogin(true);
        return;
      }
      if (status) {
        let params = {
          contentIds: id,
          selectState: 2, //未全选
          type: 4, //专辑
        };
        let res = await this.$api.user.cancelAlbum(params);
        if (res.code === 1000000) {
          this.detailData.likeState = 0;
          this.$message({
            showClose: true,
            message: this.$t("main.albumRemovedFavorite"),
            type: "warning",
          });
        }
      } else {
        let params = {
          contentId: id,
          moduleId: mId,
          type: 4, //专辑
        };
        let res = await this.$api.user.addAlbum(params);
        if (res.code === 1000000) {
          this.detailData.likeState = 1;
          this.$message({
            showClose: true,
            message: this.$t("main.albumAddedLiking"),
            type: "success",
          });
        }
      }
    },
    // 是否添加我喜欢   单曲
    async isLikeSingle(id, status) {
      if (!this.loginStatu) {
        this.setDialogLogin(true);
        return;
      }
      let res, playList;
      if (status) {
        let params = {
          contentIds: id,
          selectState: 2, //未全选
          type: 1,
        };
        res = await this.$api.user.cancelComposition(params);
        this.$message({
          showClose: true,
          message: this.$t("public.singleRemovedFavorite"),
          type: "warning",
        });
        playList = (this.playLists || []).map((val) => {
          if (val.trackId == id) {
            val.likeState = 0;
          }
          return val;
        });
      } else {
        let params = {
          contentId: id,
          moduleId: this.detailData.moduleId,
        };
        res = await this.$api.user.addComposition(params);
        this.$message({
          showClose: true,
          message: this.$t("public.singleAddedLikes"),
          type: "success",
        });
        playList = (this.playLists || []).map((val) => {
          if (val.trackId == id) {
            val.likeState = 1;
          }
          return val;
        });
      }
      if (res.code === 1000000) {
        this.getDetail();
        localStorage.setItem("__playList__", JSON.stringify(playList));
      }
    },
    // Confirm弹框
    openConfirm(type) {
      if (!this.loginStatu) {
        this.setDialogLogin(true);
        return;
      } else if (type == "addPlayList" && this.multipleSelection.length == 0) {
        this.$message({
          showClose: true,
          message: this.$t("public.selectAddSingle"),
          type: "warning",
        });
        return;
      }
      let text = "";
      if (type == "addPlayListAll" || type == "addPlayList") {
        text = this.$t("public.sureToAddToPlaylist");
      }
      this.$confirm(text, {
        confirmButtonText: this.$t("public.confirm"),
        cancelButtonText: this.$t("public.cancel"),
        showClose: false,
        // type: "warning",
        center: true,
      })
        .then(async () => {
          let addObj = {
            cover500:
              this.detailData.cover500 || this.detailData.cover200 || "",
            moduleId: this.detailData.moduleId,
            catalogueName: this.detailData.catalogueName,
            catalogueCname:
              this.detailData.catalogueCname || this.detailData.catalogueName,
            catalogueId: this.$route.params.id,
          };
          if (type == "addPlayListAll") {
            let arr = [];
            let list = arr.concat(
              ...this.detailData.works
                .filter((item) => Boolean(item.compositions))
                .map((item) => item.compositions)
            );
            list = this.utils.addArrItem(list, { musicAlbum: { ...addObj } });
            this.savePlayList({ list: list, location: "end" });
          } else if (type == "addPlayList") {
            let newArr = this.utils.addArrItem(this.multipleSelection, {
              musicAlbum: { ...addObj },
            });
            this.savePlayList({ list: newArr, location: "end" });
            this.getDetail();
          }
          this.$message({
            showClose: true,
            message: this.$t("public.addSuccess"),
            type: "success",
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //播放
    async play(type, item) {
      // if (!this.loginStatu) {
      //   this.setDialogLogin(true);
      //   return;
      // }
      console.log("list", 999);
      let addObj = {
        cover500: this.detailData.cover500 || this.detailData.cover200 || "",
        moduleId: this.detailData.moduleId,
        catalogueName: this.detailData.catalogueName,
        catalogueCname:
          this.detailData.catalogueCname || this.detailData.catalogueName,
        catalogueId: this.$route.params.id,
      };
      let arr = [];
      let list = arr.concat(
        ...this.detailData.works
          .filter((item) => Boolean(item.compositions))
          .map((item) => item.compositions)
      );
      list = this.utils.addArrItem(list, { musicAlbum: { ...addObj } });
      console.log("list", list);
      if (type == "playAll") {
        this.setPlayParentId(this.$route.params.id);
        this.setPlayClipId(null);
        // 选择播放
        if (this.multipleSelection.length > 0) {
          let selectList = this.utils.addArrItem(this.multipleSelection, {
            musicAlbum: { ...addObj },
          });
          this.savePlayList({ list: selectList, location: "start" });
          this.selectPlay({
            list: this.playLists,
            index: this.multipleSelection[0].trackId,
          });
          this.getDetail();
        } else {
          // 添加到播放列表
          this.savePlayList({ list: list, location: "start" });
          this.playAll({
            list: this.playLists,
          });
        }
      } else if (type == "play") {
        this.setPlayParentId(this.$route.params.id);
        this.setPlayClipId(null);
        this.savePlayList({ list: list, location: "start" });
        this.selectPlay({
          list: this.playLists,
          index: item.trackId,
        });
      } else if (type == "pause" || type == "pauseAll") {
        // this.setPlayParentId(null);
        this.playStatus(false);
      }
      // console.log(item)
      // let params = {
      //   trackId: item.trackId,
      //   quality: item.hifi == 1 ? "hifi" : item.kbps320 == 1 ? "320" : item.kbps192 == 1 ? "192" : item.kbps64 ? "64" : "",
      //   terminal: "Web",
      // };
      // let res = await this.$api.user.musicAddress(params);
      // // if(this.$i18n.locale === 'zh' && item.composer.fullCname){

      // // }
      // let composer = []; // 人物集
      // if (item.composer) {
      //   composer = item.composer.map(i => {
      //     if(this.$i18n.locale === 'zh' && i.fullCname){
      //       return i.fullCname;
      //     } else {
      //       return i.fullName;
      //     }
      //   })
      // }
      // // let composer =
      // this.playList = {
      //   title: this.$i18n.locale === 'zh' ? item.trackCtitle||item.trackTitle : item.trackTitle,
      //   artist: composer.join("  "),
      //   src: res.data,
      //   id: item.trackId,
      // };
      // let songInfo = {
      //   title: this.$i18n.locale === 'zh' ? item.trackCtitle||item.trackTitle : item.trackTitle,
      //   artist: composer.join("  "),
      //   params: params,
      // }
      // this.selectPlay({
      //   list: songInfo,
      //   index: item.trackId,
      // })
    },
    //分享功能
    share(type) {
      let url = `https://bshare.kuke.com/index.html?sourceType=1&sourceId=${this.$route.params.id}&moduleId=${this.detailData.moduleId}`;
      let info = {
        title:
          this.$i18n.locale == "zh"
            ? this.detailData.catalogueCname || this.detailData.catalogueName
            : this.detailData.catalogueName,
        url: encodeURIComponent(url),
        picurl: this.detailData.cover500,
      };
      let shareStr = "";
      // if (type == "weixin") {
      //   // this.dialogFormVisible = false;
      //   document.getElementById("qrcode").innerHTML = "";
      //   this.isQrcode = true;
      //   let qrcode = new QRCode("qrcode", {
      //     width: 200, // 设置宽度，单位像素
      //     height: 200, // 设置高度，单位像素
      //     text: "121.89.210.108" //info.url, // 设置二维码内容或跳转地址
      //   })
      //   console.log(qrcode)
      //   return;
      // }
      switch (type) {
        case "weixin":
          document.getElementById("qrcode").innerHTML = "";
          this.isQrcode = true;
          this.qrcodeText = "wx";
          new QRCode("qrcode", {
            width: 200, // 设置宽度，单位像素
            height: 200, // 设置高度，单位像素
            text: url, //info.url, // 设置二维码内容或跳转地址
          });
          return;
        case "weibo":
          this.isQrcode = false;
          shareStr =
            // http://v.t.sina.com.cn/share/share.php?title=
            "https://service.weibo.com/share/share.php?title=" +
            info.title +
            "&url=" +
            info.url +
            "&sharesource=" +
            "weibo" +
            // "&content=utf-8&sourceUrl=" +
            // info.url +
            "&pic=" +
            info.picurl +
            "&appkey=3371995706";
          break;
        case "qq":
          shareStr =
            "https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=" +
            info.url +
            "&sharesource=qzone&title=" +
            info.title +
            "&pics=" +
            info.picurl +
            "&summary=" +
            info.title;
          break;
        // document.getElementById("qrcode").innerHTML = "";
        // this.isQrcode = true;
        // this.qrcodeText = "qq";
        // new QRCode("qrcode", {
        //   width: 200, // 设置宽度，单位像素
        //   height: 200, // 设置高度，单位像素
        //   text:
        //     "https://bshare.kuke.com/index.html?sourceType=1" +
        //     "&sourceId=" +
        //     this.$route.params.id +
        //     "&moduleId=" +
        //     this.detailData.moduleId, //info.url, // 设置二维码内容或跳转地址
        // });
        // return;
        default:
          break;
      }
      window.open(
        shareStr,
        "newwindow",
        "height=600,width=800,top=100,left=100"
      );
    },
    // 小册子与封面图
    async getBooklets(type) {
      let params = {
        catalogueId: this.$route.params.id,
        bookletFilePath: "true",
        backCoverPath: "true",
      };
      let res = await this.$api.user.booklets(params);
      if (this.flag == false) {
        this.flag = true;
        if (res.code == "success") {
          this.isBooklet = res.data.bookletFilePath
            ? res.data.bookletFilePath
            : false;
          this.isBack = res.data.backCoverPath ? true : false;
        } else {
          this.isBooklet = false;
          this.isBack = false;
        }
      } else {
        if (type == "booklet") {
          this.openDialog(type);
          // window.open(res.data.bookletFilePath, "_blank");
        } else {
          window.open(res.data.backCoverPath, "_blank");
        }
      }
    },
    // 时间戳转日期 年月日
    formateDate(value) {
      if (value == null) {
        return "";
      } else {
        let date = new Date(value);
        let y = date.getFullYear(); // 年
        let MM = date.getMonth() + 1; // 月
        MM = MM < 10 ? "0" + MM : MM;
        let d = date.getDate(); // 日
        d = d < 10 ? "0" + d : d;
        return y + "-" + MM + "-" + d;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  margin-bottom: 20px;
  .top {
    height: 224px;
    width: 100%;
    display: flex;
    margin: 32px 0;
    .el-image {
      width: 224px;
      height: 224px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .info {
      width: calc(100% - 224px - 32px);
      margin-left: 32px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .info-text {
        display: flex;
        justify-content: space-between;
        align-items: center;
        > p {
          // > a {
          //   color: #000;
          //   border-bottom: 1px solid #000;
          //   margin-right: 32px;
          //   font-weight: 400;
          //   text-decoration: none;
          //   cursor: pointer;
          // }
          .booklet,
          .back {
            color: #000;
            &:hover {
              color: #a1322c;
            }
            &.is-disabled {
              filter: alpha(opacity=30); /*IE滤镜，透明度50%*/
              -moz-opacity: 0.3; /*Firefox私有，透明度50%*/
              opacity: 0.3; /*其他，透明度50%*/
              &:hover {
                color: none;
              }
            }
          }
        }
        .albumNum {
          color: #a1322c;
        }
      }
    }
  }
  .content {
    .first {
      > h6 {
        display: table;
        margin: 14px 0 24px 0;
        cursor: pointer;
      }
      > .checkAll {
        margin-bottom: 33px;
        .el-button,
        .icon-button {
          margin-left: 56px;
        }
      }
      .pArtist {
        height: 60px;
        line-height: 60px;
        padding: 0 16px;
        margin-bottom: 16px;
        background-color: #f5f5f5;
        span {
          margin-right: 20px;
          color: #666666;
          font-size: 18px;
        }
      }
      .icon-off-detail {
        width: 18px;
        height: 18px;
        margin: 0 8px;
      }
      .el-table {
        .workIndex {
          margin: 0 6px;
        }
        .isWorkName {
          color: #000;
          cursor: pointer;
        }
        .isSingleName {
          margin-left: 63px;
          margin-top: 5px;
          font-size: 16px;
          color: #999999;
          &.isWorkName {
            margin-left: 40px;
          }
        }
        .icon-pause {
          display: none;
        }
        .playing {
          .icon-pause {
            display: flex;
          }
          .icon-play {
            display: none;
          }
        }
      }
    }
    .second {
      > ul {
        > li {
          display: flex;
          align-items: flex-start;
          // line-height: 100%;
          margin-top: 20px;
          color: #000;
          font-weight: 500;
          line-height: 22px;
          font-family: PingFangSC-Medium, PingFang SC;
          // font-size: 16px;
          > span {
            white-space: nowrap;
          }
          p {
            > span {
              margin-right: 20px;
            }
            // color: #a1322c;
            // .router-link-exact-active {
            //   margin-right: 15px;
            //   color: #a1322c;
            //   text-decoration: none;
            // }
          }
        }
      }
    }
  }
}
.el-select {
  width: 100%;
}
// .disabled {
//   pointer-events: none;
//   filter: alpha(opacity=30); /*IE滤镜，透明度50%*/
//   -moz-opacity: 0.3; /*Firefox私有，透明度50%*/
//   opacity: 0.3; /*其他，透明度50%*/
//   cursor: default;
// }
// .fixed-aplayer {
//   width: 100%;
//   min-height: 160px;
//   position: fixed;
//   bottom: 0;
//   left: 0;
//   z-index: 9;
//   box-shadow: 0 -4px 10px #f5f5f5;
//   background: #fff;
//   .a-player {
//     width: 1200px;
//     height: auto;
//     margin: 20px auto;
//   }
// }
.el-dialog {
  .dialogShare {
    display: flex;
    justify-content: space-around;
    > li {
      cursor: pointer;
      > img {
        width: 48px;
        height: 48px;
      }
    }
  }
  .share-dialog-footer {
    text-align: center;
    .clearBtn {
      width: 200px;
      margin-bottom: 20px;
    }
    .el-button--primary {
      display: none;
    }
  }
  .qrcodeText {
    margin: 10px 0;
    text-align: center;
    font-size: 22px;
  }
  #qrcode {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
